''''''''''''''''''''''''''''''''''''''''''''''
' Enventory
'
' vbscript toolset to support administration, Enventory and control of AD Users and PC assets
'
' Copyright (C) ' by ufe@gmx.de
' started  July/August 2008, 
' based on work done within ::
'''''''''''''''''''''''''''''''''''
' Open Audit                  '
' http://open-audit.org	      '
' Software and Hardware Enventory '
' Outputs into MySQL          '
' (c) Mark Unwin 2003         '
'''''''''''''''''''''''''''''''''''
'
' This program is free software; you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation; either version 2 of the License, or
' (at your option) any later version.

' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU General Public License for more details.

' You should have received a copy of the GNU General Public License along
' with this program; if not, write to the Free Software Foundation, Inc.,
' 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
'

Option Explicit

Public Suitename: Suitename= "E-nventory"
Public SuiteProg : SuiteProg = "signVBS"

Dim EnventoryLogDir
Dim EnventoryDataDir
Dim EmailFrom
Dim EmailTo
Dim DDEEVV
Dim DBhistoryDays
Dim DBhistoryUnique
Dim DBTablePerComputer
Dim DBTablePerOU
Dim DBTableVersion : DBTableVersion = "0.6"
Dim RUNFrequence

Dim WSHFileSignature

Dim EmailCc
Dim EmailServer
Dim EMailPort

Dim MyTypeMemo 
Dim MyTypeAutoincrement
Dim MyTablePrefix

Dim  NtpServer
' Below calls the config and tool files to setups.

Dim myScriptNameExExt
Dim myScriptNameExExtExt
myScriptNameExExt=Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName,".") -1)
myScriptNameExExtExt=Left(myScriptNameExExt,InStrRev(myScriptNameExExt,".")-1)


ExecuteGlobal CreateObject("Scripting.FileSystemObject").OpenTextFile(myScriptNameExExtExt & ".conf.vbs").ReadAll
If Err.Number <> 0 Then
			wscript.echo WScript.ScriptFullName & "::" & myScriptNameExExtExt & ".conf.vbs " & Err.Number & " -- " &  Err.Description
			Err.Clear
End If
ExecuteGlobal CreateObject("Scripting.FileSystemObject").OpenTextFile(myScriptNameExExt & ".conf.vbs").ReadAll
If Err.Number <> 0 Then
			wscript.echo WScript.ScriptFullName & "::" &  myScriptNameExExt & "<<.conf.vbs" & Err.Number & " -- " &  Err.Description
			Err.Clear
End If 

'On Error Goto 0

Const ForReading = 1
Const ForWriting = 2 
Const ForAppending = 8

public ToolsTimerStartTime
public ToolsTimerEndTime

REM Dim oScrSig, oFso, sigfile, sigstatus, scriptpath, showGUI
REM Const ftotest = "enventory.SignVBS.vbs"

REM showGUI = False
REM set oScrSig = WScript.CreateObject("Scripting.Signer")
REM set oFso = WScript.CreateObject("Scripting.FileSystemObject")
REM scriptpath = oFso.GetParentFolderName(WSCript.ScriptFullName) & "\"

REM sigfile = scriptpath & ftotest

REM oScrSig.SignFile sigfile, "E-nventory"    ' try to sign the file.
REM sigstatus = oScrSig.VerifyFile(sigfile, showGUI)    ' verify the signature.
 REM If sigstatus then
  REM WScript.Echo "Signature verified for " & ftotest
 REM Else
  REM WScript.Echo "Signature **FAILED** verification for " & ftotest
 REM End If

Call Main()

Public Sub Main()
	if DDEEVV = True then on error goto 0 else on error resume next
	call ToolsTimerStart()
	dim scriptpath
	
	if DDEEVV = True then on error goto 0 else on error resume next
	dim oFso
	
	set oFso = WScript.CreateObject("Scripting.FileSystemObject") 
	scriptpath = oFso.GetParentFolderName(WSCript.ScriptFullName) & "\" 
	if DDEEVV = True then wscript.echo ( "-Verification ------ " & scriptpath )
	LogFileWrite ( "-Verification ------ " & scriptpath )
	CertCheck(scriptpath)
	if DDEEVV = True then wscript.echo ( "-Signing ------ " & scriptpath )
	LogFileWrite ( "-Signing ----------- " & scriptpath )
	CertSign(scriptpath)
	if DDEEVV = True then wscript.echo ( "-Verification ------ " & scriptpath )
	LogFileWrite ( "-Verififaction ------" & scriptpath )
	CertCheck(scriptpath)
	
	if DDEEVV = True then on error goto 0 else on error resume next
	LogFileWrite(WScript.ScriptFullName & " Execution Time: " & ToolsTimerGet()  & " seconds.")	
End Sub

public function CertCheck( folder)
	dim objSigner
	dim objFSO
	dim objFolder
	dim objFile
	dim colListOfFiles
	dim blnShowGUI
	dim blnIsSigned
	dim myErrNo
	
	blnshowGUI = false	
	set objSigner = WScript.CreateObject("Scripting.Signer")
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objFolder = objFSO.GetFolder(folder)
	Set colListOfFiles = objFolder.Files
	'on error resume next
	For each objFile in colListOfFiles
		If Right(LCASE(objFile.Name), 3) = "vbs" or Right(LCASE(objFile.Name), 3) = "bat" Then
			blnIsSigned = objSigner.VerifyFile(objFile.Path, blnShowGUI)
			if err.number<>0 then
				myErrNo = err.Number
				myErrDesc=err.description
				LogFileWrite ( "signing KO " & objFile.Name & " " & hex(myErrNo) & " -- " &  myErrDesc)
				err.Clear
				if DDEEVV = True then wscript.echo ("signing KO " & objFile.Name & " " & hex(myErrNo) & " -- " &  myErrDesc) 
				err.Clear
			else
				'wscript.echo objFile.Path & " " & "ITCertTest"
			end if 
			If blnIsSigned then
				LogFileWrite ( "signing ok " & objFile.Name )
				if DDEEVV = True then wscript.echo ("signing ok " & objFile.Name ) 
			Else
				LogFileWrite("signing KO" & objFile.Name )
				if DDEEVV = True then wscript.echo ("signing KO " & objFile.Name ) 
			End If
		else
			if DDEEVV = True then wscript.echo "Skiping   ", objFile.Path
			logfilewrite "Skiping   " & objFile.Path
		End If
	Next
end function

public function CertSign( folder)
	dim objSigner
	dim objFSO
	dim objFolder
	dim objFile
	dim colListOfFiles
	dim blnShowGUI
	dim blnIsSigned
	dim myErrNo
	
	blnshowGUI = false	
	set objSigner = WScript.CreateObject("Scripting.Signer")
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objFolder = objFSO.GetFolder(folder)
	Set colListOfFiles = objFolder.Files
	'on error resume next
	For each objFile in colListOfFiles
		If Right(LCASE(objFile.Name), 3) = "vbs" or Right(LCASE(objFile.Name), 3) = "bat" Then
			on error resume next
			objSigner.SignFile objFile.Path, WSHFileSignature, "my"
			if err.number<>0 then
				myErrNo = err.Number
				myErrDesc=err.description
				LogFileWrite ( "signed  KO " & "Cert:" & WSHFileSignature & " " & objFile.Name & " " &  hex(myErrNo) & " -- " &  myErrDesc)
				err.Clear
				if DDEEVV = True then wscript.echo ("signed  KO Cert:" & WSHFileSignature & " " & objFile.Name &  " " & hex(myErrNo) & " -- " &  myErrDesc) 
				err.Clear
			else
				LogFileWrite ( "signed  ok Cert:" & WSHFileSignature & " " & objFile.Name )
				if DDEEVV = True then wscript.echo ("signed  ok Cert:" & WSHFileSignature & " " & objFile.Name ) 
				
			end if 
		else
			if DDEEVV = True then wscript.echo "Skiping   ", objFile.Path
			logfilewrite "Skiping   " & objFile.Path
		End If
	Next
end function
 

public function ToolsTimerStart()
	ToolsTimerStartTime = Timer
end function

public function ToolsTimerStop()
	ToolsTimerEndTime = Timer
end function

public function ToolsTimerGet()
	if DDEEVV = True then on error goto 0 else on error resume next
	if ToolsTimerEndTime = 0 then call ToolsTimerStop end if
	ToolsTimerGet = ToolsTimerEndTime - ToolsTimerStartTime
	'wscript.echo WScript.ScriptFullName & "::" &  "timer " & ToolsTimerGet & " " & ToolsTimerEndTime & " " & ToolsTimerStartTime
end function

Function UserNameGet()
	if DDEEVV = True then on error goto 0 else on error resume next
	Dim objNET
		Dim StrUserName
	Set objNET = WScript.CreateObject("WScript.Network")
	UserNameGet = objNET.UserName
	if DDEEVV = true then On Error Goto 0
End Function

Function ComputerNameGet()
	if DDEEVV = True then on error goto 0 else on error resume next
	Dim objNET
	Dim StrComputerName
	Set objNET = WScript.CreateObject("WScript.Network")
	ComputerNameGet = objNET.ComputerName
	if DDEEVV = true then On Error Goto 0
End Function

'************************************
' TIMEZONE
'************************************
Public Function myTimeZone
	if DDEEVV = True then on error goto 0 else on error resume next
	dim os
	Const frmMinutes = false
	dim myTZ
    for each os in GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem")
		if frmMinutes = false then
			myTZ = os.CurrentTimeZone/60 & ":" & right("00" & os.CurrentTimeZone mod 60, 2)
			if os.CurrentTimeZone >= 0 then
				myTimeZone = "GMT+" & cstr(myTZ)
			else
				myTimeZone = "GMT" & cstr(myTZ)
			end if
		else
			myTZ = os.CurrentTimeZone
		end if
		
	next
	
	'wscript.echo myTimeZone
	REM dim oShell
	REM dim stn
	REM dim atb
	REM dim bias
	
	REM set oShell = CreateObject("WScript.Shell")  
    REM stn = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" & _  
        REM "Control\TimeZoneInformation\StandardName"  
 
    REM atb = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" & _  
        REM "Control\TimeZoneInformation\ActiveTimeBias"  
		
	REM bias = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" & _  
        REM "Control\TimeZoneInformation\Bias"  
	 
    REM wscript.echo oShell.RegRead(stn) & "( " & oShell.RegRead(bias)/60 & "::" & oShell.RegRead(atb)/60 & ")" 
	
end function

Public Function TimeZoneOld
	if DDEEVV = True then on error goto 0 else on error resume next
	Dim RegularExpressionObject
	Dim objWMIService
	Dim colItems, objItem
	if DDEEVV = True then on error goto 0 else on error resume next
	Set RegularExpressionObject = New RegExp
	Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
	Set colItems = objWMIService.ExecQuery("Select * from Win32_TimeZone")
	For Each objItem In colItems
		'   LogFileWrite( "Bias: " & objItem.Bias
		'   LogFileWrite( "Caption: " & objItem.Caption
		With RegularExpressionObject
			.Pattern = ".*\((.*)\).*"
			.IgnoreCase = True
			.Global = True
		End With
		TimeZone=RegularExpressionObject.Replace(objItem.Caption, "$1")
		
	Next
	If Err.Number <> 0 Then
			LogFileWrite "mail not sent: " & Err.Number & " -- " &  Err.Description & " " & subject
			Err.Clear
			TimeZone = " "
	End If
	
End Function

public DMmyDate
public DBmyEntryDate
public DBmytime
Dim DBmyEntryDateStr
Dim DBmyTimeStr
Dim DBmyTZStr
 
Dim sScriptNameExExt
Dim sScriptNameExExtExt

Function DBSetDateTime
	if DDEEVV = True then on error goto 0 else on error resume next
	Dim myEntryDatetime(2)
	If IsEmpty(DMmyDate) Then  ' freeze time for whole run
 		DMmyDate= date()
 		DBmytime= Time()
	End If 
		
	DBmyTZStr = myTimeZone ()
	DBmyEntryDateStr = Year(DMmyDate) & "-" & Right("00" & Left(Int(Month(DMmyDate)), 2), 2) & "-" & Right("00" & Left(Int(Day(DMmyDate)), 2), 2)
	If DDEEVV = True Then
 		DBmyTimeStr = FormatDateTime(DBmytime, 3)
 	Else
 		DBmyTimeStr = "00:00"
 	End If
	DBmyEntryDate =  DatePart("m", DMmyDate) & "/" & DatePart("d", DMmyDate) & "/" & DatePart("yyyy", DMmyDate)
	myEntryDatetime(0) = DBmyEntryDateStr
	myEntryDatetime(1) = DBmyTimeStr
	
	DBSetDateTime = myEntryDatetime
	if DDEEVV = true then On Error Goto 0
End Function

'************************************
' LOG File
'************************************

Public Function LogFileWrite(Message)	
	if DDEEVV = True then on error goto 0 else on error resume next
	Dim objLOGFileFSO ' the log file 
	Dim objLOGFile ' the log file 
	
	'wscript.echo ("LogFileWrite(" & Message & ")")
	Set objLOGFileFSO = CreateObject("Scripting.FileSystemObject")
	Set objLOGFile = LogFileOpen (objLOGFileFSO)
	'DBmyEntryDateStr = Year(DBmyEntryDate) & "-" & Right("00" & Left(Int(Month(DBmyEntryDate)), 2), 2) & "-" & Right("00" & Left(Int(Day(DBmyEntryDate)), 2), 2)
	REM If DDEEVV = True Then
 		REM DBmyTimeStr = FormatDateTime(DBmytime, 3)
 	REM Else
 		REM DBmyTimeStr = "00:00"
 	REM End If
	
	objLOGFile.Write( DBmyEntryDateStr & " " & DBmyTimeStr & " " & myTimeZone () & " " & UserNameGet() & "@" & ComputerNameGet() & " " & Message & VbCrLf)
	If Err.Number <> 0 Then
			Err.Clear
			'wscript.quit
	end if
	objLOGFile.close : 	Set objLOGFile = Nothing :	Set objLOGFileFSO = Nothing
	if DDEEVV = true then On Error Goto 0
End Function

dim logfileopenfirst 
logfileopenfirst = true

Public Function LogFileOpen (objmyLOGFileFSO)
	Dim strFilename, strDirectory
	Dim WaitForFile 
	Dim WaitForFileCount
	
	'wscript.echo ("LogFileOpen")
	if DDEEVV = true then On Error Goto 0 Else On Error Resume Next
	strDirectory = EnventoryLogDir & "\"
	If ToolsTimerStartTime = 0 Then
		Call ToolsTimerStart
	End If
	
	Call DBSetDateTime 
	if logfileopenfirst = true then
		logfileopenfirst = false
		makeDirectory (strDirectory)
		DelOld (strDirectory) 	
	end if
		
	sScriptNameExExt=Left(WScript.ScriptName, InStrRev(WScript.ScriptName,"."))
	strFileName=sScriptNameExExt & DBmyEntryDateStr & ".log"
	
	WaitForFile = True
	WaitForFileCount = 10
	Do 
		if DDEEVV = True then on error goto 0 else on error resume next
		Set LogFileOpen = objmyLOGFileFSO.OpenTextFile(strDirectory & strFileName, ForAppending, True)	
		If Err.Number <> 0 Then
			Err.Clear
			WScript.sleep DBWaitForFile  * Abs(11 - WaitForFileCount)
			WaitForFileCount = WaitForFileCount - 1
		Else
			WaitForFile=False
		End If
		If (WaitForFileCount = 0) Then
			WScript.quit 
		End If
	Loop Until WaitForFile = False
	if DDEEVV = true then On Error Goto 0
End Function

Public Function LogFileClose
	if DDEEVV = false then On Error Resume Next 
    LogFileWrite(WScript.ScriptFullName & " Execution Time: " & ToolsTimerGet()  & " seconds.")	
	CloseIE
End Function

'''''''''''''''''''''''''''''''''''''''''''''''''''
' This method is responsible for creating a directory
' The directory can be several layers deep, and if the
' parent directories don't exist, it creates them.
' If the directory already exists, it is left alone
''''''''''''''''''''''''''''''''''''''''''''''''

sub makeDirectory (newPath)
	'if DDEEVV = true then wscript.echo WScript.ScriptFullName & "::" & "MakeDirectory " & newPath
	if DDEEVV = True then on error goto 0 else on error resume next
	
	Dim myArray,length,count,path,outputFileObject
	
	Set outputfileObject = CreateObject("Scripting.FileSystemObject")
	
	if outputfileObject.FolderExists(newPath) then
		'if DDEEVV = true then wscript.echo WScript.ScriptFullName & "::" & "Dir: " & newPath & " already exists" 
		exit sub
	end if
	
	path = ""
	count = 0
	myArray = split(newPath, "\")
	length = ubound(myArray)
	while count <= length 
		path = path + myArray(count) + "\"
		count = count + 1
		if not outputfileObject.FolderExists(path) then 
			outputfileObject.CreateFolder(path)
		end if
	wend
	'if DDEEVV = true then wscript.echo WScript.ScriptFullName & "::" & "Created Dir: "&newPath&""
	
end sub

public function myFilesDirGet()
    dim wshShell
	Set WshShell = Wscript.CreateObject("Wscript.Shell")
	myFilesDirGet=WshShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Personal")
	
end function

'' SIG '' Begin signature block
'' SIG '' MIID6AYJKoZIhvcNAQcCoIID2TCCA9UCAQExDjAMBggq
'' SIG '' hkiG9w0CBQUAMGYGCisGAQQBgjcCAQSgWDBWMDIGCisG
'' SIG '' AQQBgjcCAR4wJAIBAQQQTvApFpkntU2P5azhDxfrqwIB
'' SIG '' AAIBAAIBAAIBAAIBADAgMAwGCCqGSIb3DQIFBQAEEBvC
'' SIG '' reEOQFj376E+eD9ZVYqgggISMIICDjCCAXegAwIBAgIQ
'' SIG '' fduYp37PJolB2l4qUoy9tjANBgkqhkiG9w0BAQQFADAV
'' SIG '' MRMwEQYDVQQDEwplLW52ZW50b3J5MB4XDTEwMTIzMTIz
'' SIG '' MDAwMFoXDTE2MTIzMTIzMDAwMFowFTETMBEGA1UEAxMK
'' SIG '' ZS1udmVudG9yeTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
'' SIG '' gYkCgYEAxoqL8otb0bZl/B6QNeNKa7wgv9FzkgeuH0/K
'' SIG '' Mqta3uf+k/JJF0eRdm/e+R17t2Fy0nn4kkfK/0339ZKA
'' SIG '' j+LrC6N0Z2XzotG2Tf5CR2XYHwGWtXvL1edczqrPEwnJ
'' SIG '' Bep8Fki6p0/CSSFueWSjRmMr3nP5+PNnMWarU/OyVdep
'' SIG '' yDMCAwEAAaNfMF0wEwYDVR0lBAwwCgYIKwYBBQUHAwMw
'' SIG '' RgYDVR0BBD8wPYAQlJeutLm/XtOFAEGETQ1/HKEXMBUx
'' SIG '' EzARBgNVBAMTCmUtbnZlbnRvcnmCEH3bmKd+zyaJQdpe
'' SIG '' KlKMvbYwDQYJKoZIhvcNAQEEBQADgYEAKFw68m9BqK1a
'' SIG '' mJUm2YxwCsT3mWy4nilgTWlC+wj64jouYVSY1Ozhm7L8
'' SIG '' ALBzVvvFCeHMHmvpN4pZdqzAf9CnTcNWPkYBq5Hep2aM
'' SIG '' by6t/JiG9lPhC327WWW5IQV3T+FtK2G1qW9UMGi83PMV
'' SIG '' FhUJeBp5hhxXhWORlcBZg5aiVpgxggFAMIIBPAIBATAp
'' SIG '' MBUxEzARBgNVBAMTCmUtbnZlbnRvcnkCEH3bmKd+zyaJ
'' SIG '' QdpeKlKMvbYwDAYIKoZIhvcNAgUFAKBsMBAGCisGAQQB
'' SIG '' gjcCAQwxAjAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3
'' SIG '' AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEV
'' SIG '' MB8GCSqGSIb3DQEJBDESBBD1c/fi2GSMNL45cZtABGhD
'' SIG '' MA0GCSqGSIb3DQEBAQUABIGAjGJOw9zK+yePg8etYroh
'' SIG '' lqgrmS+LhVJMmSy7aqc3ArTJB3uVpa0hv+7DsL5M7oUI
'' SIG '' yA6+yHRZGtlSd62iUJ0tQYrOToHsLs/3TVWmTetdYr5Z
'' SIG '' 9vcSuIA9NNhtGu52mrj/LwU5zOCjT/J8dLi6suqU3sWI
'' SIG '' 0N+7ak5m913ePt5qqdM=
'' SIG '' End signature block
